package com.mz.ozy.activity.c2c;

import androidx.core.content.ContextCompat;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.AdapterView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.mz.ozy.R;
import com.mz.ozy.adapter.PhotoAdapter;
import com.mz.ozy.base.BaseActivity;
import com.mz.ozy.bean.OrderDetailBean;
import com.mz.ozy.bean.OrderListBean;
import com.mz.ozy.bean.ReceiveAccountBean;
import com.mz.ozy.constants.Constants;
import com.mz.ozy.mvp.presenter.SellKtPresenter;
import com.mz.ozy.mvp.view.SellKtContract;
import com.mz.ozy.utils.SPUtils;
import com.mz.ozy.utils.StringUtils;
import com.mz.ozy.utils.ToastUtils;
import com.mz.ozy.utils.Utils;
import com.mz.ozy.widget.CustomGridView;
import com.mz.ozy.widget.dialog.ConfirmCollectDialog;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.Arrays;

public class SellKtActivity extends BaseActivity<SellKtContract.View, SellKtPresenter> implements SellKtContract.View {

    @BindView(R.id.tv_usdt_num)
    TextView mTvUsdtNum;
    @BindView(R.id.tv_sell_state)
    TextView mTvSellState;
    @BindView(R.id.tv_buykt_price)
    TextView mTvBuyktPrice;
    @BindView(R.id.tv_buykt_num)
    TextView mTvBuyktNum;
    @BindView(R.id.tv_count_down)
    TextView mTvCountDown;

    @BindView(R.id.tv_real_name)
    TextView mTvRealName;
    @BindView(R.id.tv_tele_num)
    TextView mTvTeleNum;
    @BindView(R.id.tv_order_num)
    TextView mTvOrderNum;
    @BindView(R.id.tv_pay_num)
    TextView mTvPayNum;
    @BindView(R.id.tv_order_time)
    TextView mTvOrderTime;

    //    @BindView(R.id.ll_buykt_middle)
//    LinearLayout mLlBuyktMiddle;
    @BindView(R.id.ll_buykt_bottom)
    LinearLayout mLlBuyktBottom;
    @BindView(R.id.tv_order_confirm)
    TextView mTvOrderConfirm;
    @BindView(R.id.tv_order_appeal)
    TextView mTvOrderAppeal;
    @BindView(R.id.tv_order_cancel)
    TextView mTvOrderCancel;
    @BindView(R.id.ll_count_down)
    LinearLayout mLlCountDown;


    @BindView(R.id.ll_buy_appeal)
    LinearLayout mLlBuyAppeal;
    @BindView(R.id.tv_appeal_msg)
    TextView mTvAppealMsg;
    @BindView(R.id.tv_appeal_time)
    TextView mTvAppealTime;
    @BindView(R.id.gridview)
    CustomGridView mGridView;

    @BindView(R.id.rl_pay_num)
    RelativeLayout mRlPayNum;
    @BindView(R.id.divider1)
    View divider1;
    @BindView(R.id.tv_name_label)
    TextView mTvNameLabel;
    @BindView(R.id.tv_tele_label)
    TextView mTvTeleLabel;
    @BindView(R.id.tv_pay_unit)
    TextView mTvPayUnit;

    private String orderid;
    private int type;
    private int ordertype;
    private String titleStr = "";
    private OrderDetailBean orderDetailBean;

    @SuppressLint("HandlerLeak")
    private Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    mPresenter.geAssetsInfo(SellKtActivity.this, orderid);
                    break;
                case 2:
                    final Long timeInt = (Long) msg.obj;
                    final String dateStr = long2DateStr(timeInt);
                    mTvCountDown.setText(dateStr);
                    break;
                default:
                    break;

            }
        }
    };

    /*定义一个倒计时的内部类*/
    class MyCount extends CountDownTimer {
        public MyCount(long millisInFuture, long countDownInterval) {
            super(millisInFuture, countDownInterval);
        }

        @Override
        public void onFinish() {
            handler.sendEmptyMessage(1);
        }

        @Override
        public void onTick(long millisUntilFinished) {
            Message msg = new Message();
            msg.what = 2;
            msg.obj = millisUntilFinished / 1000;
            handler.sendMessage(msg);
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sell_kt);
        ButterKnife.bind(this);
        initTitle();
        orderid = getIntent().getStringExtra("id");
        type = getIntent().getIntExtra("type", 0);
        ordertype = getIntent().getIntExtra("ordertype", 0);
        initView();
    }

    private void initView() {
        switch (type) {
            case 1:
                titleStr = "KT";
                mTvPayUnit.setText("CNY");
                break;
            case 3:
                titleStr = "KT";
                mTvOrderConfirm.setText("确认收款");
                mTvPayUnit.setText("USDT");
                break;
            case 5:
                titleStr = "KT";
                mTvOrderConfirm.setText("我已收款");
                mTvPayUnit.setText("CNY");
                break;
            case 2:
                titleStr = "股权积分";
                mTvPayUnit.setText("CNY");
                break;
            case 4:
                titleStr = "股权积分";
                mTvOrderConfirm.setText("确认收款");
                mTvPayUnit.setText("USDT");
                break;
            case 6:
                titleStr = "股权积分";
                mTvOrderConfirm.setText("我已收款");
                mTvPayUnit.setText("CNY");
                break;
        }
        String atype = getIntent().getStringExtra("atype");
        if ("0".equals(atype)) {
            tvCenterTitle.setText("卖出" + titleStr);
        } else {
            tvCenterTitle.setText("出售" + titleStr);
        }
        if (ordertype == 1) {
            mTvNameLabel.setText("卖家实名");
            mTvTeleLabel.setText("卖家手机号");
        }

        mGridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                final PhotoAdapter adapter = (PhotoAdapter) mGridView.getAdapter();
                PhotoScanActivity.startPhotoScan(SellKtActivity.this, adapter.getCourseList(), position);
            }
        });
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (ordertype == 2) {
            mPresenter.geAssetsInfo(this, orderid);
        } else {
            mPresenter.geAssetsInfo(this, orderid);
            mPresenter.queryAccount(this);
        }
    }

    @OnClick({R.id.tv_order_confirm, R.id.tv_order_appeal, R.id.tv_copy1, R.id.tv_copy2
            , R.id.tv_copy3, R.id.tv_copy4, R.id.tv_order_cancel})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_order_confirm:
                showSportsHarmDialog();
                break;
            case R.id.tv_order_appeal:
                Intent intent1 = new Intent(this, AppealActivity.class);
                intent1.putExtra("id", orderid);
                intent1.putExtra("userType", "1");
                startActivity(intent1);
                break;
            case R.id.tv_order_cancel:
                mPresenter.cancelOrder(SellKtActivity.this, orderid);
                break;
            case R.id.tv_copy1:
                copyMsg(mTvRealName.getText().toString().trim());
                break;
            case R.id.tv_copy2:
                copyMsg(mTvTeleNum.getText().toString().trim());
                break;
            case R.id.tv_copy3:
                copyMsg(mTvOrderNum.getText().toString().trim());
                break;
            case R.id.tv_copy4:
                copyMsg(mTvPayNum.getText().toString().trim());
                break;
        }
    }

    private void copyMsg(String msg) {
        if (!TextUtils.isEmpty(msg)) {
            ClipboardManager cm = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
            ClipData mClipData = ClipData.newPlainText("msg", msg);
            cm.setPrimaryClip(mClipData);
            ToastUtils.showToast("复制成功");
        }
    }

    private void showSportsHarmDialog() {
        ConfirmCollectDialog mSportsHarmDialog = new ConfirmCollectDialog(this);
        mSportsHarmDialog.setOnDialogListener(new ConfirmCollectDialog.onDialogListener() {
            @Override
            public void onSubmit(String msg) {
                submitPayOrder(msg);
                mSportsHarmDialog.toggleDialog();
            }

            @Override
            public void onCancel() {
                mSportsHarmDialog.toggleDialog();
            }
        });
        mSportsHarmDialog.toggleDialog();
    }

    private void submitPayOrder(String msg) {
        mPresenter.onPay(this, orderid, msg);
    }

    @Override
    public void geAssetsInfoSuccess(OrderDetailBean bean) {
        orderDetailBean = bean;
        if (ordertype == 2) {
            mTvRealName.setText(bean.getUsername());
            mTvTeleNum.setText(bean.getPhone());
        }
        final OrderDetailBean.OrderMapBean orderMap = bean.getOrderMap();
        if (orderMap != null) {
            mTvBuyktPrice.setText(getString(R.string.buy_kt_price_format, StringUtils.formattingDecimal(orderMap.getBuyprice(), 2)));
            mTvBuyktNum.setText(getString(R.string.buy_kt_num_format, orderMap.getNum() + titleStr));
            if (1 == orderMap.getOrdertype()) {
                setSellState(orderMap.getState());
            } else {
                setBuyState(orderMap.getDateOfExpiry(), orderMap.getState());
            }
            mTvOrderTime.setText(orderMap.getInttime());
            mTvOrderNum.setText(orderMap.getTesq());
            mTvPayNum.setText(orderMap.getPaymentVoucher());
            switch (orderMap.getTranType()) {
                case 3:
                case 4:
                    final String usdtbycny = SPUtils.getInstance(this).getString(Constants.SPName.USDTBYCNY, "");
                    mTvUsdtNum.setText(Utils.decimalUtils(new BigDecimal(orderMap.getAmount()).divide(new BigDecimal(usdtbycny)) + ""));
                    break;
                case 5:
                case 6:
                default:
                    mTvUsdtNum.setText(StringUtils.formattingDecimal(orderMap.getAmount(), 2));
                    break;
            }
        }
    }

    @Override
    public void onPaySuccess(OrderDetailBean bean) {
        ToastUtils.showToast("已确认收款");
        mPresenter.geAssetsInfo(this, orderid);
    }

    @Override
    public void queryAccountSuccess(ReceiveAccountBean bean) {
        mTvRealName.setText(bean.getUsername());
        String phone = SPUtils.getInstance(this).getString(Constants.SPName.USER, "");
        mTvTeleNum.setText(phone);
    }

    @Override
    public void cancelOrderSuccess(OrderListBean bean) {
        ToastUtils.showToast("取消成功");
        if (ordertype == 2) {
            mPresenter.geAssetsInfo(this, orderid);
        } else {
            mPresenter.geAssetsInfo(this, orderid);
            mPresenter.queryAccount(this);
        }
    }

    private void setSellState(int state) {
        mRlPayNum.setVisibility(View.GONE);
        divider1.setVisibility(View.GONE);
        mLlBuyktBottom.setVisibility(View.GONE);
        mLlCountDown.setVisibility(View.GONE);
        switch (state) {
            case 0:
                mTvSellState.setText("未成交");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                mTvOrderCancel.setVisibility(View.VISIBLE);
                break;
            case 5:
            case 7:
                mTvSellState.setText("部分成交");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                mTvOrderCancel.setVisibility(View.VISIBLE);
                break;
            case 4:
            case 6:
                mTvSellState.setText("完全成交");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 9:
                mTvSellState.setText("部分成交取消");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                mTvOrderCancel.setVisibility(View.GONE);
                break;
            case 10:
                mTvSellState.setText("已取消");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                mTvOrderCancel.setVisibility(View.GONE);
                break;
        }
    }

    private MyCount mc;

    private void setBuyState(String dateOfExpiry, int state) {
        switch (state) {
            case 0:
                mTvSellState.setText("待付款");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                mLlBuyktBottom.setVisibility(View.GONE);
                startCountDown(dateOfExpiry, 0);
                break;
            case 1:
                mTvSellState.setText("待确认");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));
                startCountDown(dateOfExpiry, 1);
                break;
            case 5:
                mLlCountDown.setVisibility(View.GONE);
                mTvOrderAppeal.setVisibility(View.GONE);
                mTvSellState.setText("申诉中");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_519bff));

                mLlBuyAppeal.setVisibility(View.VISIBLE);
                final OrderDetailBean.AppleMapBean appleMap = orderDetailBean.getAppleMap();
                mTvAppealMsg.setText(appleMap.getAppealReason());
                mTvAppealTime.setText(appleMap.getCreateTime().substring(0, appleMap.getCreateTime().length() - 2));
                final String[] imageStr = appleMap.getAppealAttachment().split(",");
                PhotoAdapter adapter = new PhotoAdapter(this, Arrays.asList(imageStr));
                mGridView.setAdapter(adapter);
                break;
            case 2:
            case 4:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("已完成");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 3:
                mLlCountDown.setVisibility(View.GONE);
                mLlBuyktBottom.setVisibility(View.GONE);
                mTvSellState.setText("已取消");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 8:
                mLlCountDown.setVisibility(View.GONE);
                mTvSellState.setText("超时未确认");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
            case 11:
                mLlCountDown.setVisibility(View.GONE);
                mTvSellState.setText("超时未付款");
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
                break;
        }
    }

    private void startCountDown(String dateOfExpiry, int type) {
        try {
            final long nowInt = Utils.getCurDateIntTime();
            final long endtimeInt = Utils.parseDateIntTime(dateOfExpiry);
            if (endtimeInt > nowInt) {
                final long spaceTimeInt = endtimeInt - nowInt;
                final String dateStr = long2DateStr(spaceTimeInt / 1000);
                mTvCountDown.setText(dateStr);
                mc = new MyCount(spaceTimeInt, 1000);
                mc.start();
            } else {
                mLlCountDown.setVisibility(View.GONE);
                if (type == 0) {
                    mTvSellState.setText("超时未支付");
                } else {
                    mTvSellState.setText("超时未确认");
                }
                mTvSellState.setTextColor(ContextCompat.getColor(this, R.color.c_333333));
            }
        } catch (ParseException e) {
            e.printStackTrace();
        }
    }

    private String long2DateStr(Long timeInt) {
        final int h = Utils.generateH(timeInt);
        final int m = Utils.generateM(timeInt);
        final int s = Utils.generateS(timeInt);
        String timestr = "";
        if (h >= 10) {
            timestr = timestr + h;
            timestr = timestr + ":";
        } else {
            if (h > 0) {
                timestr = timestr + "0" + h;
                timestr = timestr + ":";
            }
        }
        if (m >= 10) {
            timestr = timestr + m;
        } else {
            timestr = timestr + "0" + m;
        }
        timestr = timestr + ":";
        if (s >= 10) {
            timestr = timestr + s;
        } else {
            timestr = timestr + "0" + s;
        }
        return timestr;
    }
}
